package com.creditease.mobile.rss.ui;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.creditease.mobile.BaseActivity;
import com.creditease.mobile.R;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.rss.dao.RssDB;
import com.creditease.mobile.rss.dao.RssItemDB;
import com.creditease.mobile.rss.model.RssItemModel;
import com.creditease.mobile.rss.model.RssModel;
import com.creditease.mobile.rss.servicew.FeedServices;
import com.creditease.mobile.rss.ui.adapter.RssAdapter;
import com.creditease.mobile.util.ExceptionUtil;
import com.creditease.mobile.util.LogUtil;
import com.creditease.mobile.util.NetUtil;
import com.creditease.mobile.util.RssDownloadTask;
import de.nava.informa.core.ParseException;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;

public class HomeActivity extends BaseActivity {
    private final static String TAG = HomeActivity.class.getName();
    private FeedServices feedServices;
    private ListView gridView;
    private RssDB db;
    private RssItemDB itemDb;
    private TextView titleText;
    private EditText addRssEditText;
    private Handler handler;

    private ImageView reflushView;
    private static final int MSG_SUCCESS = 0;//
    private static final int MSG_FAILURE = 1;//
    private static final int ADD_SUCCESS = 2;//
    private static final int ADD_FAILURE = 3;//
    private static final int MODEL_SUCCESS = 4;//
    private ProgressBar progressBar;
    private RssAdapter adapter;
    private List<RssModel> rssList;
    public static int screenWidth;
    public static int screenHeight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.home);
        //getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
        feedServices = new FeedServices(getApplicationContext());

        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();

        db = new RssDB(getApplicationContext());
        itemDb = new RssItemDB(getApplicationContext());
        rssList = loadData();
        adapter = new RssAdapter(getApplicationContext(), rssList);
        // 标题
        titleText = (TextView) findViewById(R.id.titleText);
        titleText.setText(R.string.main_news);
        // 获得GridView实例
        gridView = (ListView) findViewById(R.id.gridView);

        // 将GridView和数据适配器关联
        gridView.setAdapter(adapter);
        reflushView = (ImageView) findViewById(R.id.reflushIcon);
        reflushView.setAdjustViewBounds(true);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        // 给刷新按钮 添加刷新事件
        reflushView.setOnClickListener(new ReflushClickListener());
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {

                switch (msg.what) {
                    case MSG_SUCCESS:// 将进度条可见
                        reflushRss();
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(getApplicationContext(), "刷新成功", Toast.LENGTH_LONG).show();
                        break;
                    case ADD_SUCCESS:
                        reflushRss();
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(getApplicationContext(), "添加RSS成功", Toast.LENGTH_LONG).show();
                        break;
                    case ADD_FAILURE:
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(getApplicationContext(), R.string.rssUrlValid, Toast.LENGTH_LONG)
                                .show();
                        break;
                    default:
                        reflushRss();
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_LONG)
                                .show();
                }
            }
        };
        // 事件监听
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                final RssModel item = (RssModel) parent.getItemAtPosition(position);
                String url = item.url;
                String idStr = item.id;
                String title = item.title;
                final Intent intent = new Intent();
                intent.setClass(HomeActivity.this, ListRssActivity.class);
                intent.putExtra("title", title);
                intent.putExtra("url", url);
                intent.putExtra("id", idStr);
                // 刷新
                List<RssItemModel> items = itemDb.findByPart(idStr, 0, 1);
                if (!idStr.equals("1") && (items == null || items.isEmpty())) {
                    if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                        Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_LONG)
                                .show();
                        return;
                    }
                    final ProgressDialog dialog = showDailog("数据加载中，请稍候...");
                    // dialog.show();
                    final String fidString = idStr;
                    // 首次加载数据
                    Thread refrushThread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            try {
                                feedServices.refrush(fidString);
                                // RssModel model=db.findById(fidString);
                                // 设置为 已读
                                if (!item.isRead) {
                                    item.isRead = true;
                                    item.isSub = true;
                                    db.updateById(item);
                                }
                                startActivity(intent);
                                adapter.updateView();
                            } catch (Exception e) {
                                Toast.makeText(getApplicationContext(),
                                        R.string.loadingErr,
                                        Toast.LENGTH_LONG).show();
                            } finally {
                                dialog.cancel();
                            }
                            Looper.loop();
                        }
                    });
                    // handler.post(refrushThread);
                    refrushThread.start();
                } else {
                    // 设置为 已读
                    if (!item.isRead) {
                        item.isRead = true;
                        item.isSub = true;
                        db.updateById(item);
                    }
                    startActivity(intent);
                    adapter.updateView();
                }
            }
        });
        gridView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                menu.setHeaderTitle(R.string.homeGridmenu);
                menu.add(1, 1, 1, R.string.rssDel);
                menu.add(1, 2, 2, R.string.rssEmpty);
                menu.add(1, 3, 3, R.string.btnCancel);
            }
        });
        gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                RssModel item = (RssModel) parent.getItemAtPosition(position);
                String url = item.url;
                String idStr = item.id;
                delId = Integer.valueOf(idStr);
                return false;
            }
        });
    }

    private int delId = 0;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getGroupId() == 1 && item.getItemId() == 1) {
            // 删除Rss
            Log.d(TAG, "delete rss id=" + delId);
            if (RssConst.FAV_ID.equals(String.valueOf(delId))) {
                Toast.makeText(getApplicationContext(), R.string.delValid, Toast.LENGTH_LONG)
                        .show();
                return super.onContextItemSelected(item);
            }
            // 删除文章
            itemDb.deleteBySectionId(String.valueOf(delId));
            // 删除RSS
            db.delete(delId);

            Toast.makeText(getApplicationContext(), R.string.delOK, Toast.LENGTH_LONG).show();
            reflushRss();
        } else if (item.getGroupId() == 1 && item.getItemId() == 2) {
            Log.d(TAG, "empty rss id=" + delId);
            // 清空数据
            if (RssConst.FAV_ID.equals(String.valueOf(delId))) {
                Toast.makeText(getApplicationContext(), R.string.delValid, Toast.LENGTH_LONG)
                        .show();
                return super.onContextItemSelected(item);
            }
            // 删除文章
            itemDb.deleteBySectionId(String.valueOf(delId));
            reflushRss();
            Toast.makeText(getApplicationContext(), R.string.delOK, Toast.LENGTH_LONG).show();
        }
        return super.onContextItemSelected(item);
    }

    public void reflushRss() {
        List<RssModel> list = loadData();
        rssList.clear();
        rssList.addAll(list);
        adapter.notifyDataSetChanged();
        adapter.updateView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 1, R.string.menu_addRss).setIcon(R.drawable.icon_more_sections);
        menu.add(0, 2, 2, R.string.menu_sub).setIcon(R.drawable.menu_section_manage);
        menu.add(0, 3, 3, R.string.menu_reflush).setIcon(R.drawable.menu_download);
        menu.add(0, 4, 4, R.string.menu_backup).setIcon(R.drawable.menu_copy);
        menu.add(0, 5, 5, R.string.menu_restore).setIcon(R.drawable.menu_refresh);
        menu.add(0, 6, 6, R.string.menu_setting).setIcon(R.drawable.menu_setting);
        //        menu.add(0, 7, 7, R.string.menu_about);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            addRssEditText = new EditText(this);
            addRssEditText.setText("http://");
            new AlertDialog.Builder(this).setTitle(R.string.addRssDesc)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setView(addRssEditText)
                    .setPositiveButton(R.string.btnOK, new AddRss())
                    .setNegativeButton(R.string.btnCancel, null)
                    .show();
        } /*else if (item.getItemId() == 7) {
            Toast.makeText(getApplicationContext(), R.string.app_about, Toast.LENGTH_LONG).show();
        }*/ else if (item.getItemId() == 3) {
            // 刷新所有订阅 Rss
            reflushAllRss();
        } else if (item.getItemId() == 4) {
            // 备份订阅 Rss

            new AlertDialog.Builder(this).setTitle("确认备份订阅？").setMessage("确认备份订阅将覆盖原有的备份")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setPositiveButton(R.string.btnOK, new BackUpRss())
                    .setNegativeButton(R.string.btnCancel, null)
                    .show();
        } else if (item.getItemId() == 5) {
            // 恢复订阅 Rss
            new AlertDialog.Builder(this).setTitle("确认恢复订阅？").setMessage("确认恢复订阅不会删除现有的订阅")
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setPositiveButton(R.string.btnOK, new RestoreRss())
                    .setNegativeButton(R.string.btnCancel, null)
                    .show();

        } else if (item.getItemId() == 6) {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), SettingActivity.class);

            startActivity(intent);
        } else if (item.getItemId() == 2) {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), RssSubActivity.class);

            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private int rssCount = 0;
    private int indexCount = 0;
    private RssDownloadTask task;

    // 刷新所有订阅 Rss
    private void reflushAllRss() {
        // 如果网络不可用
        if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
            handler.obtainMessage(MSG_FAILURE).sendToTarget();
            return;
        }
        // 将进度条可见
        progressBar.setVisibility(View.VISIBLE);

        task = new RssDownloadTask();
        List<RssModel> rssModels = loadData();
        rssCount = rssModels.size();
        indexCount = 0;
        task.execute(feedServices, rssModels, this);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_clear);
        reflushView.setImageBitmap(bitmap);
        reflushView.setOnClickListener(new CancelOnClickListener());
        // 初始化线程池
        /*        final ExecutorService executorService = Executors.newFixedThreadPool(2);

        List<RssModel> rssModels = loadData();
        rssCount = rssModels.size();
        for (RssModel model : rssModels) {
            Callable task = new ReflushCallable(model.id);
            executorService.submit(task);
        }*/
        //                // 关闭线程池
        //                executorService.shutdown();

    }

    public static boolean updateRss = false;

    @Override
    protected void onResume() {

        Log.d(TAG, "onResume");
        if (updateRss) {
            Log.d(TAG, "updateRss");
            reflushRss();
            updateRss = false;
        }
        super.onResume();
    }

    private class CancelOnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {

            mpDialog = showDailog("处理中，请稍候...");
            task.cancel(true);
        }
    }

    private ConcurrentHashMap<String, String> stateMap = new ConcurrentHashMap<String, String>();

    @Override
    public void reflushCallBack(boolean cancel, String... params) {

        String state = params[0];
        stateMap.put(state, state);
        indexCount++;
        Log.d(TAG, "完成：" + indexCount + ",共：" + rssCount);

        if (indexCount == rssCount || cancel) {
            adapter.updateView();
            if (stateMap.size() == 1) {
                handler.obtainMessage(MSG_SUCCESS).sendToTarget();
            } else {
                handler.obtainMessage(MSG_FAILURE).sendToTarget();
            }

            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_refresh);
            reflushView.setImageBitmap(bitmap);
            // 给刷新按钮 添加刷新事件
            reflushView.setOnClickListener(new ReflushClickListener());
            if (mpDialog != null) {
                mpDialog.cancel();
                mpDialog = null;
            }
        }
    }

    private final class ReflushCallable implements Callable {

        private String secetionId;

        /**
         * @param secetionId
         */
        public ReflushCallable(String secetionId) {
            super();
            this.secetionId = secetionId;
        }

        /**
         * Description:
         *
         * @param
         * @throws
         * @Author liong Create Date: 2012-4-10 下午4:18:04
         */
        @Override
        public Object call() throws Exception {

            try {
                RssModel model = feedServices.refrush(secetionId);
                //                rssReflushCallBack("true");
                return model;
            } catch (Exception e) {
                e.printStackTrace();
                //                rssReflushCallBack("false");
                throw e;
            }
        }
    }

    private final class ReflushClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            reflushAllRss();
        }
    }

    private final class AddRss implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String rssUrl = addRssEditText.getText().toString();
            if (rssUrl == null || rssUrl.trim().equals("")) {
                Toast.makeText(getApplicationContext(),
                        R.string.rssUrlCannotNull,
                        Toast.LENGTH_LONG).show();
            } else {
                // 将进度条可见
                progressBar.setVisibility(View.VISIBLE);
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            feedServices.saveRss(db, rssUrl);
                            handler.obtainMessage(ADD_SUCCESS).sendToTarget();
                        } catch (ParseException e) {
                            handler.obtainMessage(ADD_FAILURE).sendToTarget();
                        } catch (Exception e) {
                            handler.obtainMessage(MSG_FAILURE).sendToTarget();
                        }
                    }
                };
                Thread t = new Thread(runnable);
                t.start();
            }
        }
    }

    private final class BackUpRss implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                feedServices.backupRss();
                Toast.makeText(getApplicationContext(), R.string.backupOK, Toast.LENGTH_LONG)
                        .show();
            } catch (IOException e) {
                e.printStackTrace();
                String msg = ExceptionUtil.exception2String(e);
                LogUtil.d(msg);
                Toast.makeText(getApplicationContext(), R.string.backupERR, Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

    private final class RestoreRss implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                boolean b = feedServices.restoreRss();
                reflushRss();
                Toast.makeText(getApplicationContext(), R.string.restoreOK, Toast.LENGTH_LONG)
                        .show();
            } catch (IOException e) {
                e.printStackTrace();
                String msg = ExceptionUtil.exception2String(e);
                LogUtil.d(msg);
                Toast.makeText(getApplicationContext(), R.string.restoreERR, Toast.LENGTH_LONG)
                        .show();
            }
        }
    }

    private List<RssModel> loadData() {

        return db.findAll(false);
    }
}